//
//  SwitchAddressView.swift
//  AirTravel
//
//  Created by apple on 2021/7/30.
//

import UIKit
import FWPopupView
import Moya
import SwiftyJSON

protocol SwitchAddressDelegate:NSObjectProtocol {
    func switchAddressClick(data:Dictionary<String,Any>,type:Int)
}

class SwitchAddressView: FWPopupView {

    @IBOutlet weak var seachTf: UITextField!
    @IBOutlet weak var collView: UICollectionView!
    @IBOutlet weak var titleLab: UILabel!
    var contentView:UIView!
    weak var delegate: SwitchAddressDelegate?
    /// 用来主动取消网络请求
    var cancelableRequest: Cancellable?
    var city = ""
    let identifyPR = "PriceReusableView"
    let identifyPS = "PriceStarColl"
    var dataSouce : Array<Any>?
    var seachArray = [Any]()
    var hcp_type = 0
    var logoNumber = 0
    
    
    // 初始化时将xib中的view添加进来
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView = loadViewFromNib()
        contentView.frame = self.bounds
        contentView.backgroundColor = UIColor.white
        self.insertSubview(contentView, at: 0)
        
        self.collView.dataSource = self
        self.collView.delegate = self
        let layout1 = UICollectionViewFlowLayout.init()
        layout1.scrollDirection = .vertical
        
        layout1.itemSize = .init(width: (SCREEN_WIDTH - 30 - 18) / 4, height: 40)
        layout1.minimumInteritemSpacing = 6
        layout1.sectionInset = UIEdgeInsets.init(top: 6, left: 15, bottom: 6, right: 15)
        self.collView.collectionViewLayout = layout1
        self.collView.register(UINib.init(nibName: "PriceReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: identifyPR)
        self.collView.register(UINib.init(nibName: "PriceStarColl", bundle: nil), forCellWithReuseIdentifier: identifyPS)
        
        self.seachTf.delegate = self
    }
    
    // 初始化时将xib中的view添加进来
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    // 加载xib
    func loadViewFromNib() -> UIView {
        let className = type(of: self)
        let bundle = Bundle(for: className)
        let name = NSStringFromClass(className).components(separatedBy: ".").last
        let nib = UINib(nibName: name!, bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
        view.backgroundColor = UIColor.clear
        return view
    }
    
    //根据城市名称获取城市id接口
    func getCityCode() {
        cancelableRequest = NetWorkRequest(API1.getCityCode, completion: {[weak self] (responseString) -> (Void) in
            self?.dataSouce = responseString["data"].arrayObject
            self?.collView.reloadData()
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }
    
    //获取所有车站信息接口
    func getStationData() {
        cancelableRequest = NetWorkRequest(API1.getStationData, completion: {[weak self] (responseString) -> (Void) in
            self?.dataSouce = responseString["data"].arrayObject
            self?.collView.reloadData()
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }
    
    func positioning(city:String) {
        self.hcp_type = 0
        self.city = city
        self.getCityCode()
    }
    
    func hcp_positioning(city:String,logoNumber:Int) {
        self.logoNumber = logoNumber
        self.hcp_type = 1
        self.city = city
        self.getStationData()
    }
    
    @IBAction func backBtn(_ sender: UIButton) {
        self.hide()
        self.hideKeyboard()
    }
    
    
}

extension SwitchAddressView:UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int{
        if self.hcp_type == 1 {
            return 1
        }
        return 2
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if self.hcp_type == 1 {
            if self.seachArray.count == 0 {
                return self.dataSouce?.count ?? 0
            }else{
                return self.seachArray.count
            }
        }
        if section == 0 {
            return 1
        }else{
            if self.seachArray.count == 0 {
                return self.dataSouce?.count ?? 0
            }else{
                return self.seachArray.count
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifyPS, for: indexPath) as! PriceStarColl
        if self.hcp_type == 1 {
            if self.seachArray.count != 0 {
                let dic = self.seachArray[indexPath.row] as? Dictionary<String,Any>
                cell.contentLab.text = "\(dic?["stationName"] ?? "")"
                return cell
            }
            if let array = self.dataSouce {
                let dic = array[indexPath.row] as? Dictionary<String,Any>
                cell.contentLab.text = "\(dic?["stationName"] ?? "")"
            }
            return cell
        }
        if indexPath.section == 0 {
            cell.contentLab.text = self.city
        }else{
            if self.seachArray.count != 0 {
                let dic = self.seachArray[indexPath.row] as? Dictionary<String,Any>
                cell.contentLab.text = "\(dic?["name"] ?? "")"
                return cell
            }
            if let array = self.dataSouce {
                let dic = array[indexPath.row] as? Dictionary<String,Any>
                cell.contentLab.text = "\(dic?["name"] ?? "")"
                
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        //1.取出section的headerView
        let headerView : PriceReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: identifyPR, for: indexPath) as! PriceReusableView
        if self.hcp_type == 1 {
            headerView.titleLab.text = "地址列表"
            headerView.priceLab.isHidden = true
            return headerView
        }
        switch indexPath.section {
        case 0:
            headerView.titleLab.text = "当前定位"
        default:
            headerView.titleLab.text = "地址列表"
        }
        headerView.priceLab.isHidden = true
        return headerView
    }
    
    //header高度
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: SCREEN_WIDTH, height: 40)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        if self.hcp_type == 1 {
            if self.seachArray.count != 0 {
                let dic = self.seachArray[indexPath.row] as? Dictionary<String,Any> ?? [:]
                if self.logoNumber == 0 {
                    self.delegate?.switchAddressClick(data: dic, type: 2)
                }else{
                    self.delegate?.switchAddressClick(data: dic, type: 3)
                }
                return
            }
            if let array = self.dataSouce {
                let dic = array[indexPath.row] as? Dictionary<String,Any> ?? [:]
                if self.logoNumber == 0 {
                    self.delegate?.switchAddressClick(data: dic, type: 2)
                }else{
                    self.delegate?.switchAddressClick(data: dic, type: 3)
                }
            }
            return
        }
        if indexPath.section == 0 {
            self.delegate?.switchAddressClick(data: ["name":self.city], type: 2)
        }else{
            if self.seachArray.count != 0 {
                let dic = self.seachArray[indexPath.row] as? Dictionary<String,Any> ?? [:]
                self.delegate?.switchAddressClick(data: dic, type: 1)
                return
            }
            if let array = self.dataSouce {
                let dic = array[indexPath.row] as? Dictionary<String,Any> ?? [:]
                self.delegate?.switchAddressClick(data: dic, type: 1)
                
            }
        }
        
    }
}

extension SwitchAddressView:UITextFieldDelegate{
    func textFieldShouldReturn(_ textField: UITextField) -> Bool{
        textField.resignFirstResponder()
        self.seachArray.removeAll()
        if textField.text?.isEmpty == false{
            guard let array = self.dataSouce else { return true }
            for item in array {
                if hcp_type == 0 {
                    let dic = item as? Dictionary<String,Any>
                    let address = "\(dic?["name"] ?? "")"
                    if address.contains(textField.text ?? "") {
                        self.seachArray.append(dic!)
                    }
                }else{
                    let dic = item as? Dictionary<String,Any>
                    let address = "\(dic?["address"] ?? "")"
                    if address.contains(textField.text ?? "") {
                        self.seachArray.append(dic!)
                    }
                }
            }
            if self.seachArray.count == 0 {
                YProgressHUD.showToast("暂无该地址")
            }
        }
        
        self.collView.reloadData()
        return true
    }
}
